import { onPageScroll, onShow } from "@dcloudio/uni-app";
import { nextTick, ref } from "vue"
import { getMoment, getToDayTime } from "../../../utils/time";
import { db_getBillListDetails } from "../../db/bill-details";
import { objectAny } from "../../../options/base";
import { showModal } from "../../../utils/utils";
import { BigJs } from "../../../utils/mathBigjs";
import { baseStatusTypeToggle, baseTradeTypeToggle } from "../../utils/status-toggle";

export default {
    onPageScroll(){},
    setup() {
        const toDayDate = getMoment().format(`YYYY-MM-DD`);
        const scrollTop = ref(0)
        const datetimePickerRef = ref<any>(null);
        const uDropdownRef = ref<any>(null);
        // 当前列表数据集合
        const currentData = ref<{
            list:Array<objectAny>;
            income:string;
            payout:string;
            transfer:string;
        }>({
            income:'0.00',
            payout:'0.00',
            transfer:`0.00`,
            list:[]
        })
        const loadMoreConfig=ref<{
            pageSize:number;
            status:`more`|`loading`|`noMore`|`-1`;
            lastViewDate:number;
            text:objectAny
        }>({
            pageSize:10,
            status:`-1`,        //默认没有加载
            lastViewDate:+new Date(),
            text:{
                contentdown: '上拉加载更多数据',
                contentrefresh: '正在加载，请稍后...',
                contentnomore: '----- 暂无更多账单记录 -----'
            }
        })
        const dropdownData=ref({
            type:{
                value:``,
                title:`全部类型`,
                options:[{
                    label: `配送收入`,
                    value: 0,
                },{
                    label: `超时扣款`,
                    value: 2,
                },{
                    label: `提现扣款`,
                    value: 1,
                },{
                    label: `用户打赏`,
                    value: 5,
                }]
            },
            date:{
                value:``,
                title:toDayDate,
                scope:[`2023-03-23`]
            },
            condition:{
                value:``,
                title:`全部进度`,
                options:[{
                    label: `已到账`,
                    value: 0,
                },{
                    label: `处理中`,
                    value: 1,
                },{
                    label: `已扣款`,
                    value: 2,
                },{
                    label: `扣款中`,
                    value: 3,
                },{
                    label: `提现中`,
                    value: 4,
                }]
            }
        })
        onPageScroll((e)=>{
            scrollTop.value =e.scrollTop
        })

        onShow(()=>{
            getBillListDetails();
        })

        // 开始获取列表数据
        async function getBillListDetails(){
            if(loadMoreConfig.value.status==='loading'){
                return console.warn(`======> getMyAccountOverview 正在获取数据，无需多次获取，本次获取取消<======`)
            }
            loadMoreConfig.value.status='loading';

            let pageSize=loadMoreConfig.value.pageSize;
            if(currentData.value.list.length >= pageSize){
                loadMoreConfig.value.pageSize+=5;
                pageSize=loadMoreConfig.value.pageSize
            }
            const { type,date,condition } = dropdownData.value
            const {startTime,endTime} = getToDayTime(date.title);
            try {
                const {data,myErrCode,errMsg} =await db_getBillListDetails({
                    moneyType:type.value === `` ? -1:Number(type.value),
                    statusType:condition.value === `` ? -1:Number(condition.value),
                    startTime,
                    endTime
                });
                loadMoreConfig.value.status='more';
                if(myErrCode !== 0){
                    loadMoreConfig.value.pageSize-=5;
                    return showModal({
                        title:`异常提示`,
                        content:errMsg,
                        showCancel:false
                    }) 
                }
                const listData = data?.list as Array<objectAny>;
                if(pageSize > listData.length){ //无更多数据
                    loadMoreConfig.value.status='noMore';
                }
                const sortList = listData.sort((a,b)=>a.create_date - b.create_date)
                const newFillData = {
                    income:`0.00`,
                    payout:`0.00`,
                    transfer:`0.00`,
                    list:sortList
                }
                // 统计支出和收入
                for(let i=0;i<sortList.length;i++){
                    const {trade_type,change_amount} = sortList[i];
                    sortList[i].symbol = ``
                    // 收入
                    if(trade_type ===0 || trade_type === 3 || trade_type === 5 ){
                        newFillData.income = BigJs(change_amount).plus(newFillData.income).toFixed(3)
                        sortList[i].symbol = `+`
                    }else{
                        // 除了划转都变成支出
                        if(trade_type !== 4){
                            sortList[i].symbol = `-`
                            // 支出
                            newFillData.payout = BigJs(change_amount).plus(newFillData.payout).toFixed(3)
                        }else{
                            // 划转
                            newFillData.transfer = BigJs(change_amount).plus(newFillData.transfer).toFixed(3)
                        }
                    }
                    // 将金额元转成分 并保留两位小数
                    sortList[i].change_amount = BigJs(change_amount).div(100).toFixed(3).slice(0,-1)
                }
                // 将金额元转成分 并保留两位小数
                newFillData.income = BigJs(newFillData.income).div(100).toFixed(3).slice(0,-1)
                newFillData.payout = BigJs(newFillData.payout).div(100).toFixed(3).slice(0,-1)
                newFillData.transfer = BigJs(newFillData.transfer).div(100).toFixed(3).slice(0,-1)

                currentData.value = newFillData;
            } catch (error) {
                loadMoreConfig.value.status='more';
                console.error(`xxxxxx=> 获取 getMyAccountOverview 列表错误，错误信息如下： <=xxxxxx`)
                console.error(error)
                return showModal({
                    title:`异常提示`,
                    content:`访问过于火爆，请稍后再试`,
                    showCancel:false
                }) 
            }
        }

        function dateChange(date:string|null){
            if(date){
                dropdownData.value.date.title = date
                getBillListDetails();
            }
            uDropdownRef.value.close();
        }
        async function showDatetimePicker($event:any,type:boolean){
            if($event===2){
                await nextTick()
                if(type){
                    datetimePickerRef.value.show();
                }else{
                    datetimePickerRef.value.close();
                }
            }
        }
        function dropdownItemChange(value:number,type:'type'|`condition`){
            const { options } = dropdownData.value[type]
            const item=options.filter(it=>it.value===value)[0];
            dropdownData.value[type].title = item.label;
            getBillListDetails();
        }
        return {
            baseTradeTypeToggle,
            baseStatusTypeToggle,
            currentData,
            loadMoreConfig,
            scrollTop,
            datetimePickerRef,
            uDropdownRef,
            dropdownData,
            showDatetimePicker,
            dateChange,
            dropdownItemChange,
            getMoment
        }
    }
}